<?php
namespace Home\Controller;

use Think\Controller;

/**
*@desc 服务商后台
*/
class ApiWorksController extends CommonController {
    private $auth_status = 0;//默认：未认证
    private $user_email = null;//用户邮箱
    private $uid = null;
    private $auth_type = 1;
    private $user_name = '';
    private $white_list = array('shipeng.hou@37degree.com','dingxin@fangjia.com');

    public function __construct(){
        //是否服务商用户，且登录状态
        parent::__construct();

		//判断用户是否服务商用户
        if($this->role==1){
            redirect('/Index/index');
        }
        
        $this->getAuthStatus();
        $this->auth_status = session('37degree_auth_status');
        
        $this->user_email = session('user_email');
        $this->uid = session('uid');
        $this->auth_type = session('auth_type');
        $this->user_name = session('user_name');

        $this->assign('user_email',$this->user_email);
        if(empty($this->uid)) redirect('/member/login.html?role=company');
    }

    /**
    * @desc API
    */
    public function servicelist(){
        $page = I("get.p",1,'intval');
        $page_num = I('get.num',20,'intval');

        $service_list = array();

        if($this->uid){//登录用户
            $serviceModel = M('Services');
            $where = array();
            
            //'uid'=>$this->uid,'api_status'=>array('gt',0)
            $where['uid'] = array('eq',$this->uid);
            $where['service_status'] = array('gt','0');
            //获取用户服务数据个数
            $count = $serviceModel->where($where)->count();
            
            //该页数据列表
            $sql = "SELECT sum( if(api.api_enable=1 && api.api_status=1 && api.api_auth_status=2,1,0) ) online_num,sum( if(api.api_enable=1 && api.api_status!=-4 && api.api_auth_status!=-1,1,0) ) all_num,s.*, FROM_UNIXTIME(
                    greatest(
                        s.update_time,
                        max(ifnull(api.update_time, 0)),
                        max(ifnull(api.create_time, 0)),
                        s.create_time
                    ),
                    '%Y-%m-%d %T'
                ) greatest_update_time
            FROM
                dmp_services s
            LEFT JOIN dmp_service_apis_image api ON api.service_id = s.service_id
            WHERE
                s.uid = ".$this->uid."
            AND s.service_status > 0
            GROUP BY
                s.service_id
            ORDER BY
                all_num DESC,online_num DESC
            limit ".($page-1)*$page_num.",".$page_num;
            
            // echo $sql;die;
            $service_list = $serviceModel->query($sql);

            //服务列表(分页)
            $page_info = $this->cpage($count,$page_num);

            $this->assign('page',$page_info);
            $this->assign('auth_status',$this->auth_status);
            
            // echo "<pre>";print_r($service_list);die;
            $this->assign('list',$service_list);
            $this->assign('head_title','我的服务－云途数据市场');
            $this->assign('auth_status',$this->auth_status);

            $this->display('servicelist');

        }else{
            redirect('/member/login.html?role=company');
        }
    }

    //数据排序
    private function sortArrByField(&$array, $field, $desc = false){
       $fieldArr=array();
       foreach($array as $k=>$v){
        $fieldArr[$k]=$v[$field];
       }
       $sort=$desc==false? SORT_ASC:SORT_DESC;
       array_multisort($fieldArr,$sort,$array);
     }
     
    
    //编辑服务
    public function serviceEdit(){
        if(IS_POST){
            if($this->auth_status != 2){
                $this->ajaxReturn(array('status'=>1004,"msg"=>'未认证或认证审核未通过',"data"=>null));
            }
            $data = I('post.');

            if(empty($data['service_id'])){
                $this->ajaxReturn(array('status'=>1003,"msg"=>'无法获取服务编号',"data"=>null));
            }
            if(empty($data['service_name_en'])){
                $this->ajaxReturn(array('status'=>1003,"msg"=>'无法获取服务英文名',"data"=>null));
            }
            //新增服务编辑-规则
            $check_name = checkServiceApiName($data['service_name']);
             if(!$check_name){
                 $this->ajaxReturn(array('status'=>1004,"msg"=>'请输入正确的服务名称',"data"=>'service_name'));
             }
            $sql_data = $this->checkAddServiceData($data);
            
            // echo "<pre>";print_r($sql_data);die;
            //针对近期 后台数据被删除等因素，故每次更新服务时检测服务是否存在，不存在则新增改服务
            $service_exists_data['service'] = $sql_data['service_name_en'];
            $check_service_exists = $this->existsService($service_exists_data);
            if($check_service_exists['status']!=200){
                $this->ajaxReturn(array('status'=>$check_service_exists['status'],"msg"=>$check_service_exists['msg'],"data"=>null));
            }
            $check_service_data = json_decode($check_service_exists['result'],true);
            if($check_service_data['data']['exist']==1){//一存在
                //通知网关更新服务
                $result = $this->bgUpdateService($sql_data);
            }else{//不存在
                //通知网关更新服务
                $result = $this->bgAddService($sql_data);
            }
            //添加服务到网关时，网关不通过处理
            if($result['status']!=200){
                if($result['status']=='-10000008'){
                    $result['data'] = "service_host";
                    $result['msg'] = "连接".$sql_data['service_host']."超时";
                }
                $this->ajaxReturn($result);
            }
            
            //数据添加到数据库
            $sql_data['service_status'] = 1; //发布与否
            //$sql_data['service_auth_status'] = 1;//发布待审核
            $sql_data['service_auth_status'] = 2;//服务不需要审核
            $sql_data['service_enable'] = 0;//是否可用
            $sql_data['update_time'] = time();

            //入库
            $serviceModel = M('Services');
            
            $where['service_id'] = $sql_data['service_id'];
            $update_result = $serviceModel->where($where)->save($sql_data);

            //数据导入搜索elasticsearch库(检查api情况)-todo
            $this->_update_es_service($sql_data);

            if($update_result){
                $this->ajaxReturn(array('status'=>200,"msg"=>'更新成功',"data"=>'OK'));
            }else{
                $this->ajaxReturn(array('status'=>1003,"msg"=>'更新失败',"data"=>null));
            }
        }else{
           //获取服务service_id
            $service_id = I('get.service_id',null,'intval');
            if(!empty($service_id)){
                //读库数据
                $serviceModle = M('Services');
                $where['uid'] = $this->uid;
                $where['service_id'] = $service_id;
                $service_info = $serviceModle->where($where)->find();

                $this->assign('info',$service_info);
                $this->assign('head_title','编辑－'.$service_info["service_name"].'－云途数据市场');

                $categoryModel = D('Category');
                // $list = $categoryModel->getAllParentCategoryList();
                // $this->assign('list',$list);
                $all_category_list = $categoryModel->allCategoryList();
                //一级二级分类递归处理
                $all_category_array = recursionWithCategoroy($all_category_list);
                $all_json_category_string = json_encode($all_category_array);
                $this->assign('json_category_string',$all_json_category_string);
                
                //已选择的分类信息
                $tid = $cid = 0;
                if(!empty($service_info)){
                    $cid = $service_info['category_id']?$service_info['category_id']:0;
                    $tid = $service_info['children_category_id']?$service_info['children_category_id']:0;
                }
                $this->assign('cid',$cid);
                $this->assign('tid',$tid);

                $this->display('serviceEdit');
                
            }else{
                $this->display('serviceAdd');
            } 
        }
    }

    //预览服务
    public function serviceView(){
        //获取服务service_id
        $service_id = I('get.service_id',null,'intval');
        
        if(!empty($service_id)){
        	
            /*查询api以及关联的服务信息 */
            $sql = "select s.service_id,s.service_publisher,s.service_request_heads,s.service_response_heads,s.service_name services_name,s.service_name_en services_name_en,s.service_introduction,s.service_logo,FROM_UNIXTIME((s.update_time),'%Y-%m-%d %T') service_update_time,ifnull(api.api_id,0) api_id,ifnull(api.api_name,'该服务无API') api_name,api.api_name_en,api.api_status,api.api_auth_status,group_concat( distinct tag.name) tag_string ";
            $sql .= " from  dmp_services s left join dmp_service_apis api on api.service_id=s.service_id and api.api_status!=-4 left join dmp_service_tag ser_tag on ser_tag.service_id=s.service_id left join dmp_tag tag on tag.id=ser_tag.tag_id where s.service_id=".(int)$service_id;
            $serviceModel = M();
            
            $rs = $serviceModel->query($sql); 
            
            $data = $rs[0];
            
            if(!empty($data['service_request_heads'])){
                $data['service_request_heads'] = json_decode($data['service_request_heads'],true);
             }else{
                 $data['service_request_heads'] = '';
             }
            
            if(!empty($data['service_response_heads'])){
                $data['service_response_heads'] = json_decode($data['service_response_heads'],true);
             }else{
                 $data['service_response_heads'] = '';
             } 
            
            $this->assign('data',$rs);
            $this->assign('head_title','预览－'.$rs[0]["services_name"].'－云途数据市场');
            $this->display('serviceDetails');
        }else{
            $this->display('serviceAdd');
        }
    }

    public function getServiceApi(){
    	
    	   $service_id = I('get.service_id',null,'intval');
    	   $api_id = I('get.apiid',null,'intval');
         
         if(empty($service_id)){         
           //$this->display("serviceAdd");
           $this->ajaxReturn(array('status'=>10014,"msg"=>'服务编号为空',"apidata"=>null));
         }
    	
    	
    	//从数据库中加载api信息
        $serviceApiModel = M();
        
        /*查询api以及关联的服务信息*/
        $sql = "select api.* ";
        $sql .= " from dmp_service_apis api join dmp_services s on api.service_id=s.service_id where api.api_id=$api_id and s.service_id=$service_id";
 
        $rs = $serviceApiModel->query($sql); 
        
        //判断查询结果
        if(empty($rs) && $api_id!=0){
           $this->ajaxReturn(array('status'=>10014,"msg"=>'无此API数据',"apidata"=>null));
        }
         
        $data = $rs[0];
        //服务发布商名称
        $data['service_publisher'] = $service_publisher;
        //拼装服务地址
        $services_name_en = $data['services_name_en'];
        $api_name_en = $data['api_name_en'];
        
        $dataex_host = C('DATAEX_HOST');
        $data['api_host'] = $dataex_host.'/'.$services_name_en.'/'.$api_name_en;
        
        if(!empty($data['api_request_param'])){
        	
           $data['api_request_param'] = json_decode($data['api_request_param'],true);
        }else{
        	$data['api_request_param'] = '';
        }
        
        if(!empty($data['api_result_field'])){
           $data['api_result_field'] = json_decode($data['api_result_field'],true);
        }else{
        	$data['api_result_field'] = '';
        }
        
        if(!empty($data['api_error_codes'])){
           $data['api_error_codes'] = json_decode($data['api_error_codes'],true);
        }else{
        	
        	$data['api_error_codes'] = '';
        }
        //$data['service_request_heads'] = '';
        //$data['service_response_heads'] = '';
    	
        $sample_url = "";
        foreach($data['api_request_param'] as $k=>$v){
        	$sample_url.= "&".$v['name']."=".$v['default_value'];
        }
        $sample_url = substr($sample_url,1);
        $sample_url = str_replace(' ','',$sample_url);
        $data['api_sample_url'] = C(DATAEX_HOST)."/open/".$data['service_name_en']."/".$data['api_name_en']."?".$sample_url;
        
        
    	$this->ajaxReturn(array('status'=>200,"msg"=>'',"apidata"=>$data));
    	
    	}

    //获取该服务下在线API数据     
    public function ajaxOnlineApiNum(){
        $service_id = I('get.service_id',null,'intval');
        if(!$this->uid) $this->ajaxReturn(array('msg'=>'未登录','status'=>1002,'data'=>null));
        if(!empty($service_id)){
            $where['uid'] = $this->uid;
            $where['service_id'] = $service_id;
            $where['api_status'] = 1;//发布状态
            //$where['api_auth_status'] = 2;//审核通过状态 
            //是否有已上线api
            
            try{
                $apiModel = M('ServiceApisImage');
                $count = $apiModel->where($where)->count();
                $this->ajaxReturn(array('msg'=>'','status'=>200,'data'=>$count));
            }catch(excption $e){
                $this->ajaxReturn(array('status'=>1003,"msg"=>'系统异常,删除失败',"data"=>null));
            }
         }else{
        	 $this->ajaxReturn(array('msg'=>'无法获取服务编号','status'=>1002,'data'=>null));
         }
    }
    
    //服务删除(ajax请求)
    public function ajaxServiceDel(){
        $service_id = I('get.service_id',null,'intval');
        if(!$this->uid) $this->ajaxReturn(array('msg'=>'未登录','status'=>1002,'data'=>null));

        if(!empty($service_id)){
           $where['uid'] = $this->uid;
           $where['service_id'] = $service_id;
           $where['api_status'] = 1;//发布状态
           //$where['api_auth_status'] = 2;//审核通过状态 
           //是否有已上线api
           $apiModel = M('ServiceApisImage');
           $count = $apiModel->where($where)->count();
           if($count){
                $this->ajaxReturn(array('msg'=>'有已上线API,不能删除','status'=>1002,'data'=>null));
           }else{
                //删除操作
                $service_where['uid'] = $this->uid;
                $service_where['service_id'] = $service_id;
                $serviceModel = M('Services');
                $service_save_data = array('service_status'=>-1);//注销，删除
                $update_result = $serviceModel->where($service_where)->save($service_save_data);
                if($update_result){
                    //删除elasticsearch搜索源数据-todo
                    $this->_delete_es_service($service_id);

                    $this->ajaxReturn(array('msg'=>'删除成功','status'=>200,'data'=>'OK'));
                }else{
                    $this->ajaxReturn(array('msg'=>'删除失败','status'=>1003,'data'=>null));
                }
           }
        }else{
        	$this->ajaxReturn(array('msg'=>'无法获取服务编号','status'=>1002,'data'=>null));
        }

    }

    //添加服务
    public function add(){
        if(IS_POST){
            if($this->auth_status != 2){
                $this->ajaxReturn(array('status'=>1005,"msg"=>'未认证或认证审核未通过',"data"=>null));
            }
            $data = I('post.');
            
            //数据判断处理
            if(empty($data['service_name'])){
                $return_data = array('status'=>1,"msg"=>'请输入服务名称',"data"=>'service_name');
                $this->ajaxReturn($return_data);
            }
            //数据判断处理
            if(empty($data['service_name_en'])){
                $return_data = array('status'=>1,"msg"=>'请输入服务英文名称',"data"=>'service_name_en');
                $this->ajaxReturn($return_data);
            }           
            //数据判断处理
            if(empty($data['service_introduction'])){
                $return_data = array('status'=>1,"msg"=>'请输入服务介绍',"data"=>'service_introduction');
                $this->ajaxReturn($return_data);
            }
            //数据判断处理
            if(empty($data['service_host'])){
                $return_data = array('status'=>1,"msg"=>'请输入服务域名',"data"=>'service_host');
                $this->ajaxReturn($return_data);
            }            
            
            
            if(!empty($data['service_timeout']) && !is_numeric($data['service_timeout']) ){
                $this->ajaxReturn(array('status'=>1005,"msg"=>'超时时间必须为数字',"data"=>null));
            }
            
            //服务英文名只能是英文字母
             $check_rs = checkEnName($data['service_name_en']);
             if(!$check_rs){
             	  $this->ajaxReturn(array('status'=>1,"msg"=>'请输入正确的服务英文名',"data"=>'service_name_en'));
             	}
            
             $check_name = checkServiceApiName($data['service_name']);
             if(!$check_name){
            	 $this->ajaxReturn(array('status'=>1,"msg"=>'请输入正确的服务名称',"data"=>'service_name'));
             }
             
//           // 分类判断
//          if(empty($data['tid'])){
//              $return_data = array('status'=>1,"msg"=>'请选择服务分类',"data"=>'service_name');
//              $this->ajaxReturn($return_data);
//          }
             $data['children_category_id'] = $data['tid']?$data['tid']:0;
             unset($data['tid']);

             //根据域名对ip及端口处理
             if(!empty($data['service_host'])){
                 //多个域名的判断
                 if(stripos($data['service_host'], ',')!==false){
                     $host_array = explode(",",$data['service_host']);
                     foreach ($host_array as $hostkey=>$hostval){
                         if( !checkDomain($hostval) && !is_ip($hostval) ){
                             $this->ajaxReturn(array('status'=>1,"msg"=>'请输入正确服务域名',"data"=>'service_host'));
                         }
                     }
                 }else{
                     if( !checkDomain($data['service_host']) && !is_ip($data['service_host']) ){
                         $this->ajaxReturn(array('status'=>1,"msg"=>'请输入正确服务域名',"data"=>'service_host'));
                     }
                 }
             }else{
                 $this->ajaxReturn(array('status'=>1,"msg"=>'请输入正确的服务域名',"data"=>'service_host'));
             }
             
             
            //判断服务英文名是否存在(服务英文名全局唯一)
            $is_use = $this->service_enname_isuse(null,$data['service_name_en'],$data['service_name']);
            if(!$is_use){
               $this->ajaxReturn(array('status'=>1002,"msg"=>'服务英文名/服务名已经存在',"data"=>'service_name_en'));
            }
            
            $data['service_host'] = str_replace(array('http://','https://'), '', $data['service_host']);

            //对request headers处理
            $request_headers = array();
            if(!empty($data['service_request_heads'])){
                foreach ($data['service_request_heads'] as $reqkey=>$reqval){
                    if(!empty($reqval['name']) && !empty($reqval['value'])){
                        $request_headers[] = array('name'=>$reqval['name'],'value'=>$reqval['value']);
                    }
                }
                unset($data['service_request_heads']);
            }

            //对response headers 处理
            $response_headers = array();
            if(!empty($data['service_response_heads'])){
                foreach ($data['service_response_heads'] as $reskey=>$resval){
                    if(!empty($resval['name']) && !empty($resval['value'])){
                        $response_headers[] = array('name'=>$resval['name'],"value"=>$resval['value']);
                    }
                }
                unset($data['service_response_heads']);
            }
            
            /*获取发布商*/
            //从session中获取用户名和企业信息
            $ent_id = session('enterprise_id');
            $user_name = session('user_name');
            //获取发布商信息
            $service_publisher = "";
            if(!empty($user_name)){
               $service_publisher = $user_name;
            }else{
                if(!empty($ent_id)){
                   //从数据库中检索企业信息
                    $enterpriseModel = M('Enterprises');
                    $result = $enterpriseModel->where(array('id'=>$ent_id))->field('enterprise_name')->find();
                    
                    if(!empty($result)){
                       $service_publisher = $result['enterprise_name'];
                    }else{
                       //无法加载认证的企业信息
                    	$this->ajaxReturn(array('status'=>1005,"msg"=>'无法识别用户身份',"data"=>null));
                    }
                }else{
                    //未获取到认证信息
                	$this->ajaxReturn(array('status'=>1005,"msg"=>'无法识别用户身份',"data"=>null));
                }
            }
            
            
            //数据添加到数据库
            $sql_data = array();
            $sql_data = $data;
            $sql_data['service_request_heads'] = empty($request_headers)?'':json_encode($request_headers);
            $sql_data['service_response_heads'] = empty($response_headers)?'':json_encode($response_headers);
            $sql_data['service_status'] = 1; //发布与否
            //$sql_data['service_auth_status'] = 1;//发布待审核
            $sql_data['service_auth_status'] = 2;//服务不需要审核
            $sql_data['service_enable'] = 0;//是否可用
            $sql_data['create_time'] = $sql_data['update_time'] = time();
            $sql_data['service_publisher']=$service_publisher;
            //入库
            // echo "<pre>a";print_r($sql_data);die;

            $this->addServiceData($sql_data);
            return false;

        }else{
            if($this->auth_status !=2){
                //未认证时
                redirect('/apiworks/auth.html');
            }

            $categoryModel = D('Category');
            // $list = $categoryModel->getAllParentCategoryList();
            // $this->assign('list',$list);
            $all_category_list = $categoryModel->allCategoryList();
            //一级二级分类递归处理
            $all_category_array = recursionWithCategoroy($all_category_list);
            $all_json_category_string = json_encode($all_category_array);
            $this->assign('json_category_string',$all_json_category_string);

            $this->assign('head_title','添加服务－云途数据市场');
            $this->display('serviceAdd');    
        }
        
    }

    //对新增服务的数据判断，ajax请求中使用
    private function checkAddServiceData($data){
        //判断服务分类是否存在
        if(empty($data['category_id']) || !is_numeric($data['category_id']) ){
            $return_data = array('status'=>1001,"msg"=>'请选择服务分类',"data"=>null);
            $this->ajaxReturn($return_data);
        }
//      //二级分类信息
//      if(empty($data['tid']) || !is_numeric($data['tid']) ){
//          $return_data = array('status'=>1001,"msg"=>'请选择服务二级分类',"data"=>null);
//          $this->ajaxReturn($return_data);
//      }
        $data['children_category_id'] = $data['tid']?$data['tid']:0;
        unset($data['tid']);

        //数据判断处理
        if(empty($data['service_name']) || empty($data['service_name_en']) || empty($data['service_introduction']) || empty($data['service_logo']) || empty($data['service_host'])){
            $return_data = array('status'=>1001,"msg"=>'缺少参数',"data"=>null);
            $this->ajaxReturn($return_data);
        }
        if(!empty($data['service_timeout']) && !is_numeric($data['service_timeout']) ){
            $this->ajaxReturn(array('status'=>1002,"msg"=>'超时时间必须为数字',"data"=>null));
        }
        
        //服务英文名只能是英文字母
         $check_rs = checkEnName($data['service_name_en']);
         if(!$check_rs){
              $this->ajaxReturn(array('status'=>1002,"msg"=>'英文名格式不正确',"data"=>null));
            }
        
         //判断服务英文名称是否存在
         $is_use = $this->service_enname_isuse($data['service_id'],$data['service_name_en'],$data['service_name']);
         if(!$is_use){
             $this->ajaxReturn(array('status'=>1002,"msg"=>'服务英文名/服务名已经存在',"data"=>null));
           }
        
        //根据域名对ip及端口处理
        if(!empty($data['service_host'])){
            //多个域名的判断
            if(stripos($data['service_host'], ',')!==false){
                $host_array = explode(",",$data['service_host']);
                foreach ($host_array as $hostkey=>$hostval){
                    if( !checkDomain($hostval) && !is_ip($hostval) ){
                        $this->ajaxReturn(array('status'=>1002,"msg"=>'请填写正确域名',"data"=>null));
                    }
                }
            }else{
                if( !checkDomain($data['service_host']) && !is_ip($data['service_host']) ){
                    $this->ajaxReturn(array('status'=>1002,"msg"=>'请填写正确域名',"data"=>null));
                }
            }
        }else{
            $this->ajaxReturn(array('status'=>1002,"msg"=>'请填写正确域名',"data"=>null));
        }
        $data['service_host'] = str_replace(array('http://','https://'), '', $data['service_host']);

        //对request headers处理
        $request_headers = array();
        if(!empty($data['service_request_heads'])){
            foreach ($data['service_request_heads'] as $reqkey=>$reqval){
                if(!empty($reqval['name']) && !empty($reqval['value'])){
                    $request_headers[] = array('name'=>$reqval['name'],'value'=>$reqval['value']);
                }
            }
            unset($data['service_request_heads']);
        }
        $data['service_request_heads'] = empty($request_headers)?'':json_encode($request_headers);

        //对response headers 处理
        $response_headers = array();
        if(!empty($data['service_response_heads'])){
            foreach ($data['service_response_heads'] as $reskey=>$resval){
                if(!empty($resval['name']) && !empty($resval['value'])){
                    $response_headers[] = array('name'=>$resval['name'],"value"=>$resval['value']);
                }
            }
            unset($data['service_response_heads']);
        }
        $data['service_response_heads'] = empty($response_headers)?'':json_encode($response_headers);

        return $data;
    }

    //添加服务数据入库
    private function addServiceData($sql_data){
        //判断是否认证
        if($this->auth_status != 2){
            $this->ajaxReturn(array('status'=>1004,"msg"=>'未认证或认证审核未通过',"data"=>null));
        }
        $sql_data['uid'] = $this->uid;

        //入库
        try{
            $serviceModel = M('Services');
            // if(!$count = $serviceModel->where('service_name_en="'.$sql_data['service_name_en'].'"')->count()){
            //测试-请求后台***********start
            $bg_add_result = $this->bgAddService($sql_data);
            if($bg_add_result['status']!=200){
                if($bg_add_result['status']=='-10000008'){
                    $bg_add_result['data'] = 'service_host';
                    $bg_add_result['msg'] = "连接".$sql_data['service_host']."超时";   
                }
                $this->ajaxReturn($bg_add_result);
            }
            //测试-请求后台***********end
                $insert_result = $serviceModel->data($sql_data)->add();
                if($insert_result){
                    $this->ajaxReturn(array('status'=>200,'msg'=>'添加成功','data'=>$insert_result));
                }else{
                    $this->ajaxReturn(array('status'=>1004,'msg'=>'添加失败','data'=>null));
                }
            // }else{
            //     $this->ajaxReturn(array('status'=>1003,"msg"=>'该服务名称已存在',"data"=>null));
            // }
        }catch(excption $e){
            $this->ajaxReturn(array('status'=>1003,"msg"=>$e->getMessage(),"data"=>null));
        }

    }

        //api列表 //ajax请求
    public function apiList(){
        if(!$this->uid) redirect('/member/login.html?role=company');
        $service_id = I('get.service_id',null,'intval');
        $api_type = I('get.api_type',2,'intval');

        //所有服务信息
        $serviceModel = M('Services');
        $service_where = array('uid'=>$this->uid);
        $service_where['service_status'] = array('gt','0');
        
        $service_list = $serviceModel->where($service_where)->field('service_id,service_name,service_name_en')->order('service_name')->select();
        $this->assign('head_title','我的API－云途数据市场');
        $this->assign('service_list',$service_list);

        $this->assign('selected_service_id',$service_id);
        $this->assign('api_type',$api_type);
        $this->display();
    }

     //ajax列表请求
    public function ajaxApiList(){
        if(!$this->uid) $this->ajaxReturn(array('status'=>1006,'msg'=>'请登录','data'=>null));

        $page = I('post.page',1,'intval');
        $pagesize = I('post.pagesize',20,'intval');
        $api_type = I('post.api_type',2,'intval');//默认获取：已发布
        $service_id = I('post.service_id',null,'intval');//服务编号
        
        if($service_id==-1){
            
            $this->ajaxReturn(array('status'=>200,'msg'=>'','data'=>array()));
            
            }
        
        if(empty($service_id)){
           $this->ajaxReturn(array('status'=>10016,'msg'=>'未指定服务','data'=>null));
        }
        
        //api列表
        $table = " from dmp_service_apis apis left join dmp_services s on apis.service_id = s.service_id ";
        $apiModel = M();
        $where_str = "";
        $select_field = " apis.*,s.service_name s_service_name ";

        //拼装where条件
        if($api_type==2){
            //已经发布
            $select_field = " image.*,s.service_name s_service_name ";
            $table = " from dmp_service_apis_image image left join dmp_service_apis apis on apis.api_id=image.api_id left join dmp_services s on s.service_id=apis.service_id ";
            $select_field = " image.*,apis.api_status sapi_status,apis.api_auth_status sapi_auth_status,s.service_name s_service_name  ";
            $where_str = " and ( (image.api_status=1 and image.api_auth_status=2) )";//or (apis.api_status=0 and apis.api_auth_status=1 and apis.src_api_status=1) ) ";
        }else if($api_type==0){
            //未发布
            $where_str = " and api_status=0 and api_auth_status!=1 ";
        }else if($api_type==1){
            //待审
            $where_str = " and api_status=0 and api_auth_status=1 ";
        }else if($api_type==3){
            //审核驳回
            $where_str = " and api_status=0 and api_auth_status=3 ";
        }else if($api_type==4){
            //下架
            $table = " from dmp_service_apis apis left join dmp_services s on s.service_id=apis.service_id ";
            $select_field = " apis.*,apis.api_status sapi_status,apis.api_auth_status sapi_auth_status,s.service_name s_service_name  ";
            $where_str = " and apis.api_status=-2 ";
        }
        
        $count_sql = "select ".$select_field." ".$table." where apis.service_id=".$service_id." ".$where_str;
        // echo ($count_sql);die;
        
        
        $sql = $count_sql." order by update_time desc limit ".($page-1)*$pagesize.",".$pagesize; 
        
        $count = count( $apiModel->query($count_sql) );
        //$count = $apiModel->where($service_where)->count();

        $api_list = $apiModel->query($sql);
        //$api_list = $apiModel->where($service_where)->limit( ($page-1)*$pagesize,$pagesize)->select();
        $data = array('list'=>$api_list,"page"=>$page,"totalpage"=>ceil( $count / $pagesize ),'api_type'=>$api_type,'service_id'=>$service_id);
        $this->ajaxReturn(array('status'=>200,'msg'=>'OK','data'=>$data));

    }

    //预览api
    public function apiView(){
    
         $api_id = I('get.api_id',null,'intval');
         $service_id = I('get.service_id',null,'intval');
         
         if(empty($api_id)||empty($service_id)){
           $this->display("serviceAdd");
         }
         
        
        //从数据库中加载api信息
        $serviceApiModel = M();
        
        /*查询api以及关联的服务信息*/
        $sql = "select s.service_id,s.service_publisher,s.service_request_heads,s.service_response_heads,s.service_name services_name,s.service_name_en services_name_en,s.service_introduction,s.service_logo,FROM_UNIXTIME((s.update_time),'%Y-%m-%d %T') service_update_time,api.*,s.service_request_heads,s.service_response_heads,group_concat(distinct tag.name) tag_string ";
        $sql .= " from dmp_service_apis_image api join dmp_services s on api.service_id=s.service_id left join dmp_service_tag ser_tag on ser_tag.service_id=s.service_id and ser_tag.status=1 left join dmp_tag tag on tag.id=ser_tag.tag_id and tag.status=1 where api.api_id=$api_id and s.service_id=$service_id group by ser_tag.service_id ";
 
        $rs = $serviceApiModel->query($sql); 
        $data = $rs[0];
        
        //服务发布商名称
        //$data['service_publisher'] = $service_publisher;
        //拼装服务地址
        $services_name_en = $data['services_name_en'];
        $api_name_en = $data['api_name_en'];
        
        $dataex_host = C('DATAEX_HOST');
        $data['api_host'] = $dataex_host.'/'.$services_name_en.'/'.$api_name_en;
        //$data['api_sample_url'] = $data['api_host'].'/'.$data['api_sample_url'];
        
        if(!empty($data['api_request_param'])){
           $data['api_request_param'] = json_decode($data['api_request_param'],true);
        }else{
        	
        	$data['api_request_param'] = '';
        }
        
        if(!empty($data['api_result_field'])){
        	
           $data['api_result_field'] = json_decode($data['api_result_field'],true);
        }else{
        	
        	$data['api_result_field'] = '';
        }
        
        if(!empty($data['api_error_codes'])){
        	
           $data['api_error_codes'] = json_decode($data['api_error_codes'],true);
        }else{
        	$data['api_error_codes'] = '';
        }    
        
        if(!empty($data['service_request_heads'])){
            $data['service_request_heads'] = json_decode($data['service_request_heads'],true);
         }else{
             $data['service_request_heads'] = '';
         }    
        
        if(!empty($data['service_response_heads'])){
            $data['service_response_heads'] = json_decode($data['service_response_heads'],true);
         }else{
             $data['service_response_heads'] = '';
         }         
        
        
        $sample_url = "";
        foreach($data['api_request_param'] as $k=>$v){
        	$sample_url.= "&".$v['name']."=".$v['default_value'];
        }
        $sample_url = substr($sample_url,1);
        $sample_url = str_replace(' ','',$sample_url);
        $data['api_sample_url'] = C(DATAEX_HOST)."/open/".$data['service_name_en']."/".$data['api_name_en']."?".$sample_url;
        
       // echo print_r($data);die;
        $this->assign('head_title','预览－'.$data["api_name"].'－云途数据市场');
        $this->assign('data',$data);
        $this->display("apiDetails");
    }

    //本地预览api
    public function apiLocalview(){        
        $api_id = I('get.api_id',null,'intval');
         $service_id = I('get.service_id',null,'intval');
         
         if(empty($api_id)||empty($service_id)){
           $this->display("serviceAdd");
         }
         
        
        //从数据库中加载api信息
        $serviceApiModel = M();
        
        /*查询api以及关联的服务信息*/
        $sql = "select s.service_id,s.service_publisher,s.service_request_heads,s.service_response_heads,s.service_name services_name,s.service_name_en services_name_en,s.service_introduction,s.service_logo,FROM_UNIXTIME((s.update_time),'%Y-%m-%d %T') service_update_time,api.*,s.service_request_heads,s.service_response_heads ";
        $sql .= " from dmp_service_apis api join dmp_services s on api.service_id=s.service_id where api.api_id=$api_id and s.service_id=$service_id";
 
        $rs = $serviceApiModel->query($sql); 
         
        $data = $rs[0];
        
        //服务发布商名称
        //$data['service_publisher'] = $service_publisher;
        //拼装服务地址
        $services_name_en = $data['services_name_en'];
        $api_name_en = $data['api_name_en'];
        
        $dataex_host = C('DATAEX_HOST');
        $data['api_host'] = $dataex_host.'/'.$services_name_en.'/'.$api_name_en;
        //$data['api_sample_url'] = $data['api_host'].'/'.$data['api_sample_url'];
        
        if(!empty($data['api_request_param'])){
            
           $data['api_request_param'] = json_decode($data['api_request_param'],true);
        }else{
            $data['api_request_param'] = '';
        }
        
        if(!empty($data['api_result_field'])){
            
           $data['api_result_field'] = json_decode($data['api_result_field'],true);
        }else{
            
            $data['api_result_field'] = '';
        }
        
        if(!empty($data['api_error_codes'])){
           $data['api_error_codes'] = json_decode($data['api_error_codes'],true);
        }else{
            $data['api_error_codes'] = '';
        }   
        
        if(!empty($data['service_request_heads'])){
            $data['service_request_heads'] = json_decode($data['service_request_heads'],true);
         }else{
             $data['service_request_heads'] = '';
         }    
        
        if(!empty($data['service_response_heads'])){
            $data['service_response_heads'] = json_decode($data['service_response_heads'],true);
         }else{
             $data['service_response_heads'] = '';
         }          
        
        
        $sample_url = "";
        foreach($data['api_request_param'] as $k=>$v){
            $sample_url.= "&".$v['name']."=".$v['default_value'];
        }
        $sample_url = substr($sample_url,1);
        $sample_url = str_replace(' ','',$sample_url);
        $data['api_sample_url'] = C(DATAEX_HOST)."/open/".$data['service_name_en']."/".$data['api_name_en']."?".$sample_url;
        
       // echo "<pre>";print_r($data);die;
        $this->assign('head_title','预览－'.$data["api_name"].'－云途数据市场');
        $this->assign('data',$data);
        $this->display("apiDetails");

    }
    
    //api发布
    public function apiPublish(){
    	
         $api_id = I('get.api_id',null,'intval');
         $service_id = I('get.service_id',null,'intval');
         
         if(empty($api_id)||empty($service_id)){
           $this->ajaxReturn(array('status'=>10015,"msg"=>'服务编号或者API编号为空',"apidata"=>null));
         }
         
         $serviceApiModel = M();
         //查询是否有"待审核api"
         $check_sql = "select count(1) count from dmp_service_apis api where api_status=0 and api_auth_status=1 and api.api_id=$api_id and api.service_id=$service_id";
         $count_data = $serviceApiModel->query($check_sql);
         if(!empty($count_data) && $count_data[0]['count']>0){
            $this->ajaxReturn(array('status'=>1003,"msg"=>'API已经发布',"data"=>null));
         }

         $sql = "update dmp_service_apis api join dmp_services s on api.service_id=s.service_id set api_auth_status=1, api_status=0 where api.api_id=$api_id and s.service_id=$service_id";
         //echo print_r($sql);die;
         $update_rs = $serviceApiModel->execute($sql); 
         
         if($update_rs){
            $this->ajaxReturn(array('status'=>200,"msg"=>'API发布申请,提交成功',"data"=>'OK'));
         }else{
            $this->ajaxReturn(array('status'=>1003,"msg"=>'API发布失败',"data"=>null));
         }
    	
   }
    

    //编辑api
    public function apiEdit(){
        if(IS_POST){
            if($this->auth_status != 2){
                $this->ajaxReturn(array('status'=>1004,"msg"=>'未认证或认证审核未通过',"data"=>null));
            }
            $data = I('post.');
            if(empty($data['api_id'])){
                $this->ajaxReturn(array('status'=>1003,"msg"=>'无法获取API编号',"data"=>null));
            }
            if(empty($data['api_name_en'])){
                $this->ajaxReturn(array('status'=>1003,"msg"=>'无法获取API英文名',"data"=>null));
            }

            $sql_data = $this->checkApiAddData($data);
            
            //判断是否进行过编辑（防止重复编辑）
            $check_result = $this->checkApiStatus($sql_data['api_id']);
            if( in_array($check_result,array(-1,1,-4) ) ){
                //不可编辑状态
                if($check_result==-1)$this->ajaxReturn(array('status'=>1003,"msg"=>'请勿重复编辑，该API审核中',"data"=>null));
                if($check_result==1)$this->ajaxReturn(array('status'=>1003,"msg"=>'该API已发布，不允许编辑',"data"=>null));
                if($check_result==-4)$this->ajaxReturn(array('status'=>1003,"msg"=>'该API不存在',"data"=>null));
            }

            //检查api中文名称是否有重复，并且英文名称不改变
            $apiModle = M('ServiceApis');
            $check_where['api_name'] = $data['api_name'];
            $check_where['api_id'] = array('neq',$data['api_id']);
            $count = $apiModle->where($check_where)->count();
            if($count) $this->ajaxReturn(array('status'=>1003,"msg"=>'API英文名称已经存在',"data"=>null));

            //数据添加到数据库
            $sql_data['api_status'] = 0; //发布
            $sql_data['api_enable'] = 1;//是否可用
            $sql_data['update_time'] = time();
            // $sql_data['mini_price'] = $data['mini_price'];
            // $sql_data['api_charge_rules'] = $data['api_charge_rules'];

            unset($sql_data['api_name_en']);
            
            try{
                //入库
                //$serviceModel = M('ServiceApisImage');
                $insert_result = $apiModle->where('api_id='.$sql_data['api_id'])->save($sql_data);
                //echo $apiModle->getlastsql();die;
                if($insert_result){
                    $this->ajaxReturn(array('status'=>200,"msg"=>'更新成功',"data"=>'OK'));
                }else{
                    $this->ajaxReturn(array('status'=>1003,"msg"=>'更新失败',"data"=>null));
                }
            }catch(excption $e){
                $this->ajaxReturn(array('status'=>1003,"msg"=>'网络问题,更新失败',"data"=>null));
            }

        }else{
            //获取服务service_id
            $api_id = I('get.api_id',null,'intval');
            $api_auth_status = I('get.auth',null);
            $service_id = I('get.service_id',null);

            //判断是否进行过编辑（防止重复编辑）
            $check_result = $this->checkApiStatus($api_id);
            if(!empty($api_id)){
                if( in_array($check_result,array(-1,1,-4) ) ){
                    if(empty($service_id) || !is_numeric($service_id)){
                        redirect('/apiworks/apiList.html');            
                    }
                    switch($check_result){
                        case 1:
                            //已发布，则跳转到已发布列表
                            redirect('/apiworks/apiList.html?service_id='.$service_id."&api_type=2");
                            break;
                        case -1:
                            //待审核，则跳转到待审核列表
                            redirect('/apiworks/apiList.html?service_id='.$service_id."&api_type=1");
                            break;
                        default:
                            redirect('/apiworks/apiList.html');
                            break;
                    }
                }
                //读库数据
                $Model = M(); // 实例化一个model对象 没有对应任何数据表
                if($api_auth_status && $api_auth_status==2){
                    $api_from_table = 'dmp_service_apis_image';
                }else{
                    $api_from_table = 'dmp_service_apis';
                }
                $api_info = $Model->query("select sers.service_host,apis.*,sers.service_name from ".$api_from_table." apis left join dmp_services sers on  sers.service_id= apis.service_id  where apis.uid=".$this->uid." and apis.api_id=".$api_id);

                $api_charge_rules = json_decode($api_info[0]['api_charge_rules'],true);
                $api_info[0]['api_charge_rules'] = $api_charge_rules;
                
                $this->assign('info',$api_info[0]);
                $this->assign('head_title','编辑－'.$api_info[0]["api_name"].'－云途数据市场');
                
                if(in_array($this->user_email, $this->white_list)){
                    $this->assign('in_white_list',1);
                }else{
                    $this->assign('in_white_list',0);
                }
                $this->display('apiEdit');
            }else{
                $this->display('apiAdd');
            }
        }

    }

    //检查api状态
    private function checkApiStatus($api = null){
        if(empty($api) || !is_numeric($api)) return -4;

        $Model = M();
        $sql = "select api.api_status,api.api_auth_status,api.api_enable from dmp_service_apis api where api.api_id=".(int)$api;
        $check_result = $Model->query($sql);

        //已发布的api不能编辑（可以更新）；待审核api不能进行编辑
        if(empty($check_result)) {
            return -4;
        }

        $check_info = $check_result[0];
        if($check_info['api_status']==1 && $check_info['api_auth_status']==2){
            //已发布
            return 1;
        }else if($check_info['api_status']==0 && $check_info['api_auth_status']==1){
            //待审核
            return -1;
        }else if($check_info['api_status']==0 && $check_info['api_auth_status']==0){
            //未发布
            return -2;
        }else if($check_info['api_status']==0 && $check_info['api_auth_status']==3){
            //审核失败
            return -3;
        }else{//已删除或下架
            return -5;
        }

    }

    //已发布api=》更新页面
    public function apiUpdate(){
        //获取服务service_id
        $api_id = I('get.api_id',null,'intval');
        $api_auth_status = I('get.auth',null);

        if(!empty($api_id)){
            //读库数据
            if($api_auth_status && $api_auth_status==2){
                $api_from_table = 'dmp_service_apis_image';
            }else{
                $api_from_table = 'dmp_service_apis';
            }
            $Model = M(); // 实例化一个model对象 没有对应任何数据表
            $sql = "select sers.service_host,apis.*,sers.service_name from ".$api_from_table." apis left join dmp_services sers on  sers.service_id= apis.service_id  where apis.uid=".$this->uid." and apis.api_id=".$api_id;
            // echo $sql;die;
            $api_info = $Model->query($sql);

            $api_charge_rules = json_decode($api_info[0]['api_charge_rules'],true);
            $api_info[0]['api_charge_rules'] = $api_charge_rules;

            //先检查api是否存在，如不存在则新增----前期下线服务重新增加---由于后台数据被删
            $params['service'] = $api_info[0]['service_name_en'];
            $params['api'] = $api_info[0]['api_name_en'];
            $check_result = $this->existsApi($params);
            if($check_result['status']==200){
                $gate_result = json_decode($check_result['result'],true);
                if($gate_result['data']['exist']==0){
                    //新增api
                    $add_params['service_name_en'] = $api_info[0]['service_name_en'];
                    $add_params['api_name_en'] = $api_info[0]['api_name_en'];
                    $add_params['api_uri'] = $api_info[0]['api_uri'];
                    $add_result = $this->bgAddApi($add_params);

                }
            }

            // timp($api_info[0]);die;
            $this->assign('info',$api_info[0]);
            $this->assign('head_title','更新－'.$api_info[0]["api_name"].'－云途数据市场');

            if(in_array($this->user_email, $this->white_list)){
                $this->assign('in_white_list',1);
            }else{
                $this->assign('in_white_list',0);
            }
            $this->display('apiUpdate');
        }else{
            $this->display('apiAdd');
        }
    }

    //已发布api，更新操作（已发布1,2=》待审核0,1,1）,操作service_apis表，同时，入历史记录表
    public function apiStatusUpdate(){
          $api_id = I('post.api_id',null,'intval');
          if(empty($api_id) || !is_numeric($api_id)) $this->ajaxReturn(array('status'=>1003,"msg"=>'无法获取API编号',"data"=>null));  
          
          $data = I('post.');
          $sql_data = $this->checkApiAddData($data);

          //检查是否已经更新
          $check_result = $this->checkApiStatus($api_id);
          // echo "<pre>";print_r($check_result);die;
          if($check_result != 1){
             $this->ajaxReturn(array('status'=>1003,"msg"=>'请勿重复更新',"data"=>null));
          }

          //检查api英文名称是否有重复=====todo
          $apiModel = M('ServiceApis');
          $check_where['api_name_en'] = $data['api_name_en'];
          $check_where['api_id'] = array('neq',$data['api_id']);
          $count = $apiModel->where($check_where)->count();
          //echo $apiModel->getlastsql();die;
          if($count) $this->ajaxReturn(array('status'=>1003,"msg"=>'英文名称已经存在',"data"=>null));

          $where['api_id'] = $api_id;
          $sql_data['api_status']=0;
          $sql_data['api_auth_status']=1;
          $sql_data['src_api_status']=1;
          $sql_data['update_time'] = time();

          try{
            $update_result = $apiModel->where($where)->save($sql_data);
          }catch(exception $e){
            $this->ajaxReturn(array('status'=>1003,"msg"=>'网络异常,更新失败',"data"=>null));
          }

          if($update_result){
            $hisModel = D('ApiCheckHistory');
            $his_data = array('api_id'=>$api_id,'opt_type'=>3);
            try{
                $result = $hisModel->addInfo($his_data);
                $this->ajaxReturn(array('status'=>200,"msg"=>'更新成功',"data"=>'OK'));
            }catch(exception $e){
                $this->ajaxReturn(array('status'=>1003,"msg"=>'网络异常,更新失败',"data"=>null));
            }

          }
    }


    //ajax删除api
    public function apiDel(){
        $api_id = I('get.api_id',null,'intval');
        $service_id = I('get.service_id',null,'intval');
        if(!$this->uid) $this->ajaxReturn(array('msg'=>'未登录','status'=>1002,'data'=>null));

        if(empty($api_id) || empty($service_id)){
            $this->ajaxReturn(array('msg'=>'服务或者API编号为空','status'=>1002,'data'=>null));
            }
        
           $apiModel = M();
           
           $sql = "select api.api_status,api.api_auth_status from dmp_service_apis api join dmp_services s on api.service_id=s.service_id where api.api_id=$api_id and s.service_id=$service_id";
           $api_info = $apiModel->query($sql);
           
           if(!empty($api_info)){
                $api_info = $api_info[0];
                //已经发布的服务不能直接删除
                if($api_info['api_status']==1 && $api_info['api_auth_status'] == 2){
                    $this->ajaxReturn(array('msg'=>'发布的服务不能直接删除','status'=>1002,'data'=>null));
                    
                    }
                    
                    $del_sql = "update dmp_service_apis api join dmp_services s on api.service_id=s.service_id set api_status=-4 where api.api_id=$api_id and s.service_id=$service_id";
                    
                    $update_result = $apiModel->execute($del_sql);
                          
                    if($update_result){
                        $this->ajaxReturn(array('msg'=>'删除成功','status'=>200,'data'=>'OK'));
                    }else{
                        $this->ajaxReturn(array('msg'=>'删除失败','status'=>1003,'data'=>null));
                    }

           }else{
                $this->ajaxReturn(array('msg'=>'该API不存在','status'=>1002,'data'=>null));
           }
    }

    //已发布api，申请下架（已发布1,2=》已下架，-2,2,1），更新service_apis表
    public function apiSetDown(){
        if(empty($this->uid))$this->ajaxReturn(array('status'=>1003,"msg"=>'请重新登录',"data"=>null));

          $api_id = I('post.api_id',null,'intval');
          $api_name = I('post.api_name'); 
          $service_name = I('post.service_name');
          $api_name_en = I('post.api_name_en');
          $service_name_en = I('post.service_name_en');

          if(empty($api_id) || !is_numeric($api_id)) $this->ajaxReturn(array('status'=>1003,"msg"=>'无法获取API编号',"data"=>null)); 
          $apiModel = M('ServiceApis');
          $apiImageModel = M('ServiceApisImage');
          $where['api_id'] = $api_id;
          $api_data = array('api_status'=>-2,'api_auth_status'=>2,'src_api_status'=>1);
          
          //通知网管下架
          //echo $api_name."==".$service_name."===".$api_name_en."===".$service_name_en;die;
          $online_where = array('api_id'=>$api_id,"service_name_en"=>$service_name_en);
          $online_info = $apiImageModel->where($online_where)->find();
          // echo $apiImageModel->getlastsql();die;
          if(empty($online_info)){
                $this->ajaxReturn(array('status'=>404,"msg"=>'该服务不存在',"data"=>null)); 
          }
          $params['service'] = $service_name_en;//服务名称
          $params['api'] = $api_name_en;//api名称
          // $check_api_info = $this->existsApi($params);
          // echo "<pre>check:";print_r($check_api_info);die;
          //新增 start
          $params['api_uri'] = $online_info['api_uri'];
          $params['disable '] = 1;
          // echo "<pre>";print_r($params);
          //新增 end
          $auth_result = dmp_curl_post(C(AUTH_UPDATE_API),$params);//原先使用接口-AHTH_DELETE_API
          // echo "<pre>";print_r($auth_result);die;

          if($auth_result['status']==200){
            $auth_status = json_decode($auth_result['result'],true);
            if($auth_status['return_code']==0){
                try{
                    $update_result_image = $apiImageModel->where($where)->save($api_data);//镜像下架
                    $update_result = $apiModel->where($where)->save($api_data);
                  }catch(exception $e){
                    $this->ajaxReturn(array('status'=>1003,"msg"=>'网络问题',"data"=>null));
                  }

                  if($update_result){
                    $hisModel = D('ApiCheckHistory');
                    $his_data = array('api_id'=>$api_id,'opt_type'=>4);
                    try{
                        $result = $hisModel->addInfo($his_data);
                        //邮件王珂-好产品
                        $to = "kew@37degree.com";//
                        $title = "标题：【云途数据市场】API下架";
                        $content = apidownEmail($api_name,$service_name,$this->user_email);
                        sendMail($to, $title, $content);

                        //删除elasticsearch搜索源中api，并判断是否最后一个api，如果是最后一个api则同时删除服务--todo
                        $this->_delete_es_api($online_info);

                        $this->ajaxReturn( array('status'=>200,"msg"=>'下线成功',"data"=>'OK') );
                    }catch(exception $e){
                        $this->ajaxReturn(array('status'=>1003,"msg"=>'网络问题',"data"=>null));
                    }

                  }

            }else{
                $this->ajaxReturn(array('status'=>1003,"msg"=>'网络问题',"data"=>null));
            }

          }else{
            $this->ajaxReturn(array('status'=>1003,"msg"=>'网络问题',"data"=>null));
          }

          
    }
    
    //删除es库中api
    private function _delete_es_api($info){
        if(!isset($info['api_id'])) return false;

        //是否最后一个api,检查库中是否有上线api
        $imageModel = D('ServiceApisImage');
        $num = $imageModel->countOnlineapiWithService($info['service_id']);

        //删除api
        $url = C(ES_DEL_API);
        $url .=$info['api_id'];

        $result = dmp_es_curlrequest($url,'',$method='DELETE');
        // timp($result);die;

        //删除服务
        if($num==0){
            $url = C(ES_DEL_SERVICE);
            $url .=$info['service_id'];

            $service_result = dmp_es_curlrequest($url,'',$method='DELETE');
            // timp($service_result);die;
        }
    }

    //更新es库中服务
    private function _update_es_service($info){
        if(!isset($info['service_id'])) return false;

        //检查库中是否有上线api
        $imageModel = D('ServiceApisImage');
        $num = $imageModel->countOnlineapiWithService($info['service_id']);

        if($num){
            //更新es服务    
            $url = C('ES_SERVICE_OPTION');
            $url .= $info['service_id']; 

            $data = array(
                    "name"=>$info['service_name'],
                    'desc'=>$info['service_introduction'],
                    'provider'=>session('user_name'),
                    "sid"=>$info['service_id']
                    );
            // $data = array_merge($data,$info);

            $result = dmp_es_curlrequest($url,json_encode($data),$method='PUT');
        }

    }

    //删除es中服务---curl -XDELETE 'http://127.0.0.1:9200/dataex/service/10'
    private function _delete_es_service($service_id){
        if(empty($service_id) || !is_numeric($service_id)) return false;

        //删除服务
        $url = C(ES_DEL_SERVICE);
        $url .=$service_id;

        $result = dmp_es_curlrequest($url,'',$method='DELETE');
        // timp($result);die;
    }

    //撤回发布，撤回更新
    public function apiStatusCallback(){
       $api_id = I('post.api_id',null,'intval');
      if(empty($api_id) || !is_numeric($api_id)) $this->ajaxReturn(array('status'=>1003,"msg"=>'缺少必要参数',"data"=>null));
      $api_status = I('post.api_status',0);
      $api_auth_status = I('post.api_auth_status',0);
      $src_api_status = I('post.src_api_status',0);
      if($src_api_status==0){
        //新增待审核=》撤回
        $data['api_status'] = 0;
        $data['api_auth_status'] = 0;
        $data['src_api_status'] = 0;
      }else if($src_api_status==1){
        //更新待审核撤回，更新审核失败撤回
        $data['api_status'] = 1;
        $data['api_auth_status'] = 2;
        $data['src_api_status'] = 0;
        //镜像表数据回写到api原始表
        //todo
        $back_result = $this->imageBacktoApi($api_id);
        if($back_result==true){
            $hisModel = D('ApiCheckHistory');
            $his_data = array('api_id'=>$api_id,'opt_type'=>9);
            try{
                $result = $hisModel->addInfo($his_data);
                $this->ajaxReturn(array('status'=>200,"msg"=>'撤回成功',"data"=>'OK'));
            }catch(exception $e){
                $this->ajaxReturn(array('status'=>1003,"msg"=>'网络问题',"data"=>null));
            }
          }else{
            $this->ajaxReturn(array('status'=>1003,"msg"=>'网络问题',"data"=>null));
          }

      }else if ($src_api_status==2){
        //重新上架待审核撤回
        $data['api_status'] = -2;
        $data['api_auth_status'] = 2;
        $data['src_api_status'] = 0;
      }

      $data['update_time'] = time();
      try{
          $apiModel = M('ServiceApis');
          $where['api_id'] = $api_id;
          $result = $apiModel->where($where)->save($data);

      }catch(exception $e){
           $this->ajaxReturn(array('status'=>1003,"msg"=>'网络问题',"data"=>null));
      }
      
      if($result){
        $hisModel = D('ApiCheckHistory');
        $his_data = array('api_id'=>$api_id,'opt_type'=>9);
        try{
            $result = $hisModel->addInfo($his_data);
            $this->ajaxReturn(array('status'=>200,"msg"=>'撤回成功',"data"=>'OK'));
        }catch(exception $e){
            $this->ajaxReturn(array('status'=>1003,"msg"=>'网络问题',"data"=>null));
        }
      }

    }

    //重新上架（已下架-2,2,1=》重新上架0,1,2）
    public function apiResetUp(){
      $api_id = I('post.api_id',null,'intval');
      if(empty($api_id) || !is_numeric($api_id)) $this->ajaxReturn(array('status'=>1003,"msg"=>'缺少必要参数',"data"=>null));  

      $apiModel = M('ServiceApis');
      $where['api_id'] = $api_id;

      //网关重新上架
      $info = $apiModel->where($where)->find();
      if(empty($info)){
        $this->ajaxReturn(array('status'=>404,"msg"=>'数据不存在',"data"=>null));
      }

      // $params['service'] = $info['service_name_en'];//服务名称
      // $params['api'] = $info['api_name_en'];//api名称
      // // $check_api_info = $this->existsApi($params);
      // $params['api_uri'] = $info['api_uri'];
      // $params['disable '] = 0;

      // $gate_update_result = dmp_curl_post(C(AUTH_UPDATE_API),$params);
      // // echo "<pre>check:";print_r($gate_update_result);die;

      $api_data = array('api_status'=>0,'api_auth_status'=>1,'src_api_status'=>2,'update_time'=>time() );
      try{
        $update_result = $apiModel->where($where)->save($api_data);
      }catch(exception $e){
        $this->ajaxReturn(array('status'=>1003,"msg"=>'网络问题',"data"=>null));
      }

      if($update_result){
        $hisModel = D('ApiCheckHistory');
        $his_data = array('api_id'=>$api_id,'opt_type'=>8);
        try{
            $result = $hisModel->addInfo($his_data);
            $this->ajaxReturn(array('status'=>200,"msg"=>'API重新上线申请成功',"data"=>'OK'));
        }catch(exception $e){
            $this->ajaxReturn(array('status'=>1003,"msg"=>'网络问题',"data"=>null));
        }

      }  
    } 

    //添加api
    public function apiAdd(){
        $service_id = I('get.service_id',null,'intval');
        
        if(IS_POST){
            if(!$this->uid) $this->ajaxReturn(array('status'=>1005,'msg'=>'请重新登录','data'=>null));
            $data = I('post.');
            
            //数据判断处理
            if(empty($data['service_id'])){
                $this->ajaxReturn(array('status'=>1005,'msg'=>'无法获取服务编号','data'=>null));
            }
            
            if(empty($data['api_name'])){
                $this->ajaxReturn(array('status'=>1,'msg'=>'请输入API名称','data'=>'api_name'));   
            }
            if(empty($data['api_name_en'])){
                $this->ajaxReturn(array('status'=>1,'msg'=>'请输入服务英文名称','data'=>'api_name_en'));   
            }            
            if(empty($data['api_uri'])){
                $this->ajaxReturn(array('status'=>1,'msg'=>'请输入API地址','data'=>'api_uri'));   
            }            
            if(empty($data['api_introduction'])){
                $this->ajaxReturn(array('status'=>1,'msg'=>'请输入API介绍','data'=>'api_introduction'));   
            }            

            //判断服务是否存在(传入的service_id可以是 服务编号，也可以是服务英文名)
            $dbmodel = M();
            
            $sql = "select service_id from dmp_services where service_id=".(int)$data['service_id'];
            
            $serviceRs = $dbmodel->query($sql);
            if(empty($serviceRs)){
               $this->ajaxReturn(array('status'=>1005,'msg'=>'服务不存在','data'=>null));
            }
            //$service_id = $serviceRs['service_id'];

           
            //判断英文名是否符合规则
            if(!checkEnName($data['api_name_en'])){
            	$this->ajaxReturn(array('status'=>1,'msg'=>'请输入正确的API英文名称','data'=>'api_name_en'));
            	}
            
            $check_name = checkServiceApiName($data['api_name']);
            if(!$check_name){
           	  $this->ajaxReturn(array('status'=>1,"msg"=>'请输入正确的API名称',"data"=>'api_name'));
            }
           
           $charge_status = $data['api_is_charge'];
           if($charge_status==1){
                //校验，套餐数据
                if(empty($data['api_charge_rules'])){
                    $this->ajaxReturn(array('status'=>1,"msg"=>'请增加套餐',"data"=>'api_charge_rules'));
                }
                if(!isset($data['api_charge_rules'][0]['package_price']) || $data['api_charge_rules'][0]['package_price'] <= 0){
                    $this->ajaxReturn(array('status'=>1,"msg"=>'套餐中价格不合理',"data"=>'api_charge_rules'));
                }
                $data['min_price'] = $data['api_charge_rules'][0]['package_price'];
                $data['api_charge_rules'] = json_encode($data['api_charge_rules']);
           }else{
                unset($data['api_charge_rules']);
                $data['mini_price'] = 0;
           }
           // echo "<pre>";print_r($data);die;
            //请求参数处理
            $req_params = array();
            if(!empty($data['api_request_param'])){
                foreach ($data['api_request_param'] as $paramkey=>$paramval){
                    if(!empty($paramval['name'])){
                        $req_params[] = $paramval;
                    }
                }
            }
            
            unset($data['api_request_param']);
            //返回字段
            $return_field = array();
            if(!empty($data['api_result_field'])){
                foreach ($data['api_result_field'] as $fieldkey=>$fieldval){
                    if(!empty($fieldval['name'])){
                        $return_field[] = $fieldval;
                    }
                }
            }
            unset($data['api_result_field']);
            //错误码
            $error_code = array();
            if(!empty($data['api_error_codes'])){
                foreach ($data['api_error_codes'] as $codekey=>$codeval){
                    if(!empty($codeval['code'])){
                        $error_code[] = $codeval;
                    }
                }
            }
            unset($data['api_error_codes']);
            //数据整理
            $new_data = $data;
            $new_data['uid'] = $this->uid;
            //$new_data['$service_id']=$service_id;
            $new_data['api_request_param'] = empty($req_params)?'':json_encode($req_params);
            $new_data['api_result_field'] = empty($return_field)?'':json_encode($return_field);
            $new_data['api_error_codes'] = empty($error_code)?'':json_encode($error_code);
            $new_data['create_time'] = $new_data['update_time'] = time();
			
            //数据添加到数据库
            $this->apiDataOption($new_data);
            return true;

        }else{
            if(empty($service_id)) redirect('/apiworks/index.html');
            //获取对应服务信息
            $serviceModel = M('Services');
            
            if(is_numeric($service_id)){
            	
            	   $service_info = $serviceModel->where('service_id='.$service_id)->find();
            }else{
            	  
            	   $service_info = $serviceModel->where('service_name_en="'.$service_id.'"')->find();
            }
             
            //echo $serviceModel->getlastsql();die;
           
            if(!empty($service_info)){
                $this->assign('info',$service_info);
                $this->assign('head_title','添加API－'.$service_info["service_name"].'－云途数据市场');
                $this->display('apiAdd');
            }else{
               // $this->error('该服务链接无效');
            	redirect('/member/mailfail');
            }
            
        }
        
    }

   //判断api_name_en是否重复存在
   private function api_enname_isuse($self_api_id,$name_en){
   	 
   	 //$dbmodel = M();
   	 //$sql = "select api_id from dmp_service_apis where api_name_en='".$name_en."'";
   	 
   	 //if(!empty($self_api_id)){
   	 	// $sql.=" and api_id!=".$self_api_id;
   	 	//}
   	 
   	 //$queryRs = $dbmodel->query($sql);
   	 //if(empty($queryRs)){
   	 	//return true;
   	  //}else{
   		//return false;
   		//}
   		
   		return true;
   	}
   	
   //判断api_name_en是否重复存在
   private function service_enname_isuse($self_service_id,$name_en,$service_name){
    if(empty($this->uid)) return false;

   	 $dbmodel = M();
   	 $sql = "select service_id from dmp_services where ( service_name_en='".$name_en."'";
   	 
     $sql .=" or (uid=".$this->uid." and service_name ='".$service_name."') )";
     
   	 if(!empty($self_service_id)){
   	 	 $sql.=" and service_id!=".$self_service_id;
   	 }
   	 
   	 $queryRs = $dbmodel->query($sql);
   	 if(empty($queryRs)){
   	 	return true;
   	}else{
   		return false;
   		}
   	}

    //api保存（或添加）及 更新或添加api与大后台请求
    private function apiDataOption($data){

        $serviceApiModel = M('ServiceApis');
        if(isset($data['api_id']) && is_numeric($data['api_id']) && $data['api_id']){

        	//判断api 英文名是否重复
        	if(!$this->api_enname_isuse($data['api_id'],$data['api_name_en'])){
        		$this->ajaxReturn(array('status'=>1003,"msg"=>'该API英文名称已存在',"data"=>null));
        	  }
        	
            //更新
            $api_id = $data['api_id'];
            $update_result = $serviceApiModel->where('api_id='.$api_id)->save($data);
            if($update_result){
                //(更新记录到api记录表)
                $history_data = array('opt_type'=>3,'api_id'=>$api_id,'update_time'=>time());
                $historyModel = M('ApiCheckHistory');
                //$historyModel->addInfo($history_data);
                $historyModel->where('api_id='.$api_id)->save($history_data);

                $this->ajaxReturn(array('status'=>200,'msg'=>'更新成功','data'=>$api_id));
            }else{
                $this->ajaxReturn(array('status'=>1004,'msg'=>'更新失败','data'=>null));
            }
        }else{//新增
            

            //从数组中删除api_id，使用数据库自增id
            unset($data['api_id']);
            if(!$this->api_enname_isuse(null,$data['api_name_en'])){
    		  $this->ajaxReturn(array('status'=>1003,"msg"=>'该API英文名称已存在',"data"=>null));
    		}

            //请求网关，添加api（单api在审核通过前为屏蔽状态）
            $bg_add_api_result = $this->curlPlatformWithAddapi($data);

            if(!empty($bg_add_api_result) && isset($bg_add_api_result['return_code']) && $bg_add_api_result['return_code']==0 ){
                 $insert_result = $serviceApiModel->data($data)->add();
            }else{
                $this->ajaxReturn( array('status'=>1003,'msg'=>'请求失败('. $bg_add_api_result['return_msg'].":".$bg_add_api_result['return_code'] .')' ,'data'=>null) );
            }
           
            //添加服务,API的信息，通知大后台
            if($insert_result){
                //(新增记录到api记录表)
                $history_data = array('opt_type'=>1,'api_id'=>$insert_result);
                $historyModel = D('ApiCheckHistory');
                $historyModel->addInfo($history_data);

                $this->ajaxReturn(array('status'=>200,'msg'=>'添加成功','data'=>$insert_result));
            }else{
                $this->ajaxReturn(array('status'=>1004,'msg'=>'添加失败','data'=>null));
            }
        }

    }

    //对api提交的数据进行检测
    private function checkApiAddData($data){
        if(empty($data['service_id']) || !is_numeric($data['service_id'])){
                $this->ajaxReturn(array('status'=>1001,'msg'=>'无法获取服务编号','data'=>null));
            }
        
            if(empty($data['api_name'])){
                $this->ajaxReturn(array('status'=>1,'msg'=>'请输入API名称','data'=>'api_name'));   
            }
            if(empty($data['api_name_en'])){
                $this->ajaxReturn(array('status'=>1,'msg'=>'请输入API英文名称','data'=>'api_name_en'));   
            } 
            if(empty($data['api_uri'])){
                $this->ajaxReturn(array('status'=>1,'msg'=>'请输入API地址','data'=>'api_uri'));   
            }            
            if(empty($data['api_introduction'])){
                $this->ajaxReturn(array('status'=>1,'msg'=>'请输入API介绍','data'=>'api_introduction'));   
            }            
            
            $charge_status = $data['api_is_charge'];
           if($charge_status==1){
                //校验，套餐数据
                if(empty($data['api_charge_rules'])){
                    $this->ajaxReturn(array('status'=>1,"msg"=>'请增加套餐',"data"=>'api_charge_rules'));
                }
                if(!isset($data['api_charge_rules'][0]['package_price']) || $data['api_charge_rules'][0]['package_price'] <= 0){
                    $this->ajaxReturn(array('status'=>1,"msg"=>'套餐中价格不合理',"data"=>'api_charge_rules'));
                }
                $data['min_price'] = $data['api_charge_rules'][0]['package_price'];
                $data['api_charge_rules'] = json_encode($data['api_charge_rules']);
                
           }else{
                unset($data['api_charge_rules']);
                $data['mini_price'] = 0;
                $data['api_charge_rules'] = null;
           }

            //请求参数处理
            $req_params = array();
            if(!empty($data['api_request_param'])){
                foreach ($data['api_request_param'] as $paramkey=>$paramval){
                    if(!empty($paramval['name'])){
                        $req_params[] = $paramval;
                    }
                }
            }
            unset($data['api_request_param']);
            $data['api_request_param'] = empty($req_params)?'':json_encode($req_params);

            //返回字段
            $return_field = array();
            if(!empty($data['api_result_field'])){
                foreach ($data['api_result_field'] as $fieldkey=>$fieldval){
                    if(!empty($fieldval['name'])){
                        $return_field[] = $fieldval;
                    }
                }
            }
            unset($data['api_result_field']);
            $data['api_result_field'] = empty($return_field)?'':json_encode($return_field);

            //错误码
            $error_code = array();
            if(!empty($data['api_error_codes'])){
                foreach ($data['api_error_codes'] as $codekey=>$codeval){
                    if(!empty($codeval['code'])){
                        $error_code[] = $codeval;
                    }
                }
            }
            unset($data['api_error_codes']);
            $data['api_error_codes'] = empty($error_code)?'':json_encode($error_code);

            return $data;
    }

    //认证
    public function auth(){
        if(IS_POST){
            $auth_type = I('post.auth_type',1);
            $data = I('post.');
            if($auth_type==1){
                //个人认证
                $this->addUserAuth($data);
            }else if($auth_type==2){
                //企业认证
                $this->addEnterpriseAuth($data);
            }

        }else{
            if(empty($this->uid)) redirect('/member/login.html?role=company');
            //已认证
            $this->assign('auth_status',$this->auth_status);

            if($this->auth_status == 2){
                //企业或个人名称信息
                redirect('/apiworks/index.html');
            }else if($this->auth_status==1){
            	redirect('/apiworks/userinfo.html');
            }else{
                //读取该用户已有认证信息
                if($this->auth_status==3){//审核失败
                    $userModel = M();
                    if($this->auth_type==2){
                        $sql = "select u.auth_type,e.* from dmp_users u left join dmp_enterprises e on e.id=u.enterprise_id where u.id=".(int) $this->uid;
                        $auth_id = session('enterprise_id');
                    }else{
                        $sql = "select u.* from dmp_users u where u.id=".(int) $this->uid;
                        $auth_id = $this->uid;
                    }
                    $info = $userModel->query($sql);
                    if(!empty($info)){
                        $this->assign('info',$info[0]);
                        $this->assign('auth_id',$auth_id);
                    }
                }
            }
            $this->assign('head_title','帐号认证－云途数据市场');
            $this->display();
        }
    }

    //服务商登录后首页为 我的服务
    public function index(){
        //$this->display('servicelist');
        $this->servicelist();
    }

    //服务商基本信息
    public function userinfo(){
        $this->assign('auth_user_status',$this->auth_status);
        $this->assign('user_auth_fail',session('user_auth_fail'));
        $this->assign('head_title','帐号信息－云途数据市场');
        $this->assign('auth_type',$this->auth_type);
        
        if($this->auth_type==2){//企业认证，需要获取企业名称
            $enterprise_id = session('enterprise_id');
            $enterpriseModel = M('Enterprises');
            $where['id'] = $enterprise_id;
            $enterprise_info = $enterpriseModel->where($where)->find();
            $name = '';
            if(!empty($enterprise_info)) $name = $enterprise_info['enterprise_name'];
        }else{
            $name = session('user_name');
        }
        //echo $this->auth_type."===".$name;die;
        $this->assign('name',$name);

        $this->display();
    }


    //修改密码
    public function resetpasswd(){
        if(IS_POST){
            $old_passwd = trim( I('post.old_passwd',null) );
            $new_first_pwd = trim( I('post.new_first_pwd',null) );
            $new_second_pwd = trim ( I('post.new_second_pwd',null) );
            
            if(empty($old_passwd)){
                $this->ajaxReturn( array('status'=>1,'msg'=>'请输入密码','data'=>null) );
            }
            
            if(empty($new_first_pwd)){
                $this->ajaxReturn( array('status'=>2,'msg'=>'请输入密码','data'=>null) );
            }            
            
            //判断密码规则
            if(!checkPasswd($new_first_pwd)){
            	$this->ajaxReturn( array('status'=>2,'msg'=>'请输入6-16位字符的密码','data'=>null) );
            }
            
            if(empty($new_second_pwd)){
                $this->ajaxReturn( array('status'=>3,'msg'=>'请输入密码','data'=>null) );
            }            
            
            if($old_passwd == $new_first_pwd){
                $this->ajaxReturn( array('status'=>1001,'msg'=>'新密码与原密码不能一样','data'=>null) );
            }
            if($new_second_pwd != $new_first_pwd){
                $this->ajaxReturn( array('status'=>3,'msg'=>'请输入相同的密码','data'=>null) );
            }
            
            $user = M('Users');
            $where['user_email'] = $this->user_email;
            $user_info = $user->where($where)->find();
            if(!empty($user_info)){
                if(md5($old_passwd) == $user_info['user_passwd']){
                    $data['user_passwd'] = md5($new_first_pwd);
                    $result = $user->where($where)->save($data);
                    if($result){
                        $this->ajaxReturn( array('status'=>200,'msg'=>'密码修改成功','data'=>true) );
                    }else{
                        $this->ajaxReturn( array('status'=>1005,'msg'=>'修改密码失败','data'=>NULL) );
                    }
                }else{
                    //请输入正确原始密码
                    $this->ajaxReturn( array('status'=>1,'msg'=>'请输入正确的密码','data'=>null) );
                }
            }else{
                //需要重新登录
                $this->ajaxReturn( array('status'=>1010,'msg'=>'请重新登录','data'=>null) );
            }

        }else{
        	$this->assign('head_title','修改密码－云途数据市场');
            $this->display();
        }
    }

    //api监控列表
    public function monitorList(){
        if(empty($this->uid)) redirect('/member/login.html?role=company');
        $this->getApisListInUser();
        $this->assign('head_title','API监控－云途数据市场');
        $this->display();
    }

    //ajax请求监控数据
    public function ajaxMonitorList(){
        //page，pagesize，service_id，api_id
        $page = I('post.page',1,'intval');
        $pagesize = I('post.pagesize',20,'intval');
        $service_name_en = I('post.service_id',-1);
        $api_name_en = I('post.api_id',0);
        $cycle_type = I('post.cycle_type',5);
        $services = I('post.services');//所有服务的英文名称
        $all_services = I('post.all_services');//所有服务信息（key=>value）
        $all_apis = I('post.all_apis');//所有服务及api信息（key=>value）

        //获取全部服务监控数据
        $start_limit = $page-1;
        $end_limit = ($page-1)*$pagesize;

        //服务及api编号
        if($service_name_en==-1 && empty($services)) $this->ajaxReturn( array('status'=>200,'msg'=>'','data'=>null) );
        if($service_name_en != -1){
            //获取改用户所有服务的名称 
            $services = array($service_name_en);
        }
            
        $method = '';
        if($api_name_en) $method = $api_name_en;
        // //测试数据
        // $method = 'user_prof';
        // $services = array('kv_demo');
        // $cycle_type = 4;

        //频次，服务名称，方法名称
        $sql = $this->getTotalMonitorSql($cycle_type, $services ,$method);
        //分页限制
        // todo

        //获取数据
        $list = $this->getMonitorDataWithSql($sql,$isAjax = true);
        //映射中文名称
        if(!empty($list)){
            foreach ($list as $k=>&$v){
                $v->service_name = $all_services[$v->service];
                $v->api_name = $all_apis[$v->service][$v->method];
                $v->cycle_type = $cycle_type;//筛选的选项
            }
        }
        $this->ajaxReturn( array('msg'=>'OK','data'=>$list,'status'=>200) );

    }

    //api监控详情
    public function monitorDetail(){
        $service_name = I('get.service_name');//获取服务英文名称
        $api_name = I('get.api_name');//获取api英文名称
        $cycle_type = I('get.cycle_type',2);//获取时间周期

        //  测试数据
        // $method = 'user_prof';
        // $services = array('kv_demo');
        // $cycle_type = 4;


        $this->getApisListInUser();

        $this->assign('service_name',$service_name);
        $this->assign('api_name',$api_name);

        //获取该api的监控折线图信息
        $sql = $this->getMonitorSql($cycle_type, $services = array($service_name) ,$method = $api_name);
        $list = $this->getMonitorDataWithSql($sql);
        
        $xAxis = $cnt_ret = $cnt_call = $cnt = $count = array();
        if(!empty($list)){
            foreach ($list as $k=>$v){
                array_push($xAxis, $v->ti);
                array_push($cnt_ret, (int)$v->cnt_ret);
                array_push($cnt_call,(int)$v->cnt_call);
                array_push($cnt, (int) $v->cnt);
                array_push($count, (int) $v->count);
            }
            
        }

        $data['xAxis'] = json_encode($xAxis);
        $data['series']['cnt_ret'] = json_encode($cnt_ret);
        $data['series']['cnt_call'] = json_encode($cnt_call);
        $data['series']['cnt'] = json_encode($cnt);
        $data['series']['count'] = json_encode( $count );//test

        $this->assign('data',$data);
        //echo "<pre>";print_r($data);die;

        //获取总数数据
        $total_sql = $this->getTotalMonitorSql($cycle_type, $services = array($service_name) ,$method = $api_name);
        $total_list = $this->getMonitorDataWithSql($total_sql);
        //echo "<pre>monitorDetail";print_r($total_list);die;
        if(!empty($total_list)) $this->assign('info',$total_list[0]);
        $this->assign('cycle_type',$cycle_type);
        
        //$this->assign('head_title','监控－'.$api_name_cn.'－'.$service_name_cn.'－云途数据市场');
        $this->display();
    }

    //获取用户服务及api信息
    private function getApisListInUser(){
        if(empty($this->uid)) redirect('/member/login.html?role=company');
       //获取所有服务信息，服务下api信息（级联）

        // $serviceApiModel = M('ServiceApis');
        // $where = array(
        //     'api_auth_status'=>2,//审核状态
        //     'api_status' => 1,//已发布
        //     'uid'=>$this->uid,
        // );
        // $service_api_list = $serviceApiModel->where($where)->select();
        $serviceApiModel = D('ServiceApis');
        $service_api_list = $serviceApiModel->getAllApiInfos($this->uid);
        //echo "<pre>";print_r($service_api_list);die;
        $service_name_en_array = $service_list = $api_list = array();
        
        foreach ($service_api_list as $key=>$val){
            $service_name_en = $val['service_name_en'];
            $api_name_en = $val['api_name_en'];
            //$service_name = $val['service_name'];
            $service_name = $val['s_service_name'];
            $api_name = $val['api_name'];
            
            if(!$service_name_en) $service_name_en = "无服务名-".$key;//服务名称不存在时

            if($service_name_en && !array_key_exists($service_name_en,$service_list)){
            	$service_list[$service_name_en] = $service_name;
            	array_push($service_name_en_array, $service_name_en);
            }
            $api_list[$service_name_en][$api_name_en] = $api_name;
        }
        
        //echo "<pre>";print_r($service_list);print_r($api_list);print_r($service_name_en_array);die;
        $this->assign('parent_service',$service_list);
        $this->assign('children_service',json_encode($api_list) );
        //echo "<pre>";print_r($api_list);die;
        $this->assign('all_service_name_en',json_encode( array_unique ($service_name_en_array) ));
         
    }

    //获取监控表（折线图）sql语句
    private function getMonitorSql($cycle_type = 0, $services = array(),$method = ''){
        if(empty($services)) return null;

        $select_sql = "select ts.service,ts.method,";
        $select_sql .="to_char(
                    TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second',
                    'YYYY-MM-DD HH:MI'
                ) ti,";
        $select_sql .="decode(
                    SUM (cnt_ret),
                    NULL,
                    0,
                    SUM (cnt_ret)
                ) cnt_ret,";
        $select_sql .="decode(
                    SUM (cnt_call),
                    NULL,
                    0,
                    SUM (cnt_call)
                ) cnt_call,";
    $select_sql .="round( SUM (decode(retcode, 0, 1, 0)) / COUNT (1) :: NUMERIC * 100, 2 ) || '%' cnt,count(distinct username) count";

    $from_sql = " from t_statis ts ";

    $where_sql = " where ";
    switch($cycle_type){
        case 1:
            $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE - INTERVAL '1 hour' ";
            break;
        case 2:
            $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE ";
            break;
        case 3:
            $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE - INTERVAL '30 day' ";
            break;
        case 4:
            $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE - INTERVAL '90 day' ";
            break;
        case 0:
            $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE - INTERVAL '5 minute' ";
        case 5:
            $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE - INTERVAL '7 day' ";
            break;
        default:
            $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE ";
            break;
    }

    if(!empty($services)){
        $new_services = array();
        foreach ($services as $sk=>$sv){
            array_push($new_services, "'".$sv."'");
        }
        $serivces_string = implode(",", $new_services);
        $where_sql .= " AND ts.service in (".$serivces_string." ) ";
    }
    if(!empty($method)){
        $where_sql .=" AND ts. METHOD = '".$method."' ";
    }

    $where_sql.=" AND username!='debug@37degree.com' ";

    $group_sql = " group by ";
    $group_sql.="to_char(
                    TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second',
                    'YYYY-MM-DD HH:MI'
                ),ts.service,ts.method ";
    $order_sql = " ORDER BY 1,2,3";

    $sql = $select_sql ." ". $from_sql ." ".$where_sql." ".$group_sql." ".$order_sql;

    //echo $sql;die;
    return $sql; 
    }

    //获取监控表（总数）sql语句
    private function getTotalMonitorSql($cycle_type = 2, $services = array(),$method = ''){
        if(empty($services)) return null;

        $select_sql = "select ts.service,ts.method,";
        $select_sql .="decode(
                    SUM (cnt_ret),
                    NULL,
                    0,
                    SUM (cnt_ret)
                ) cnt_ret,";
        $select_sql .="decode(
                    SUM (cnt_call),
                    NULL,
                    0,
                    SUM (cnt_call)
                ) cnt_call,";
        $select_sql .="round( SUM (decode(retcode, 0, 1, 0)) / COUNT (1) :: NUMERIC * 100, 2 ) || '%' cnt,count(distinct username) count ";

        $from_sql = " from t_statis ts ";

        $where_sql = " where ";
        switch($cycle_type){
            case 1:
                $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE - INTERVAL '1 hour' ";
                break;
            case 2:
                $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE ";
                break;
            case 3:
                $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE - INTERVAL '30 day' ";
                break;
            case 4:
                $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE - INTERVAL '90 day' ";
                break;
            case 0:
                $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE - INTERVAL '5 minute' ";
            case 5:
                $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE - INTERVAL '7 day' ";
                break;
            default:
                $where_sql .= " TIMESTAMP 'epoch' + ts.insert_time * INTERVAL '1 second' >= CURRENT_DATE ";
                break;
        }

        if(!empty($services)){
            $new_services = array();
            foreach ($services as $sk=>$sv){
                array_push($new_services, "'".$sv."'");
            }
            $serivces_string = implode(",", $new_services);
            $where_sql .= " AND ts.service in (".$serivces_string." ) ";
        }
        if(!empty($method)){
            $where_sql .=" AND ts. METHOD = '".$method."' ";
        }

        $where_sql.=" AND username!='debug@37degree.com' ";
        
        $group_sql = " group by ts.service,ts.method ";

        $sql = $select_sql ." ". $from_sql ." ".$where_sql." ".$group_sql;

        return $sql; 
    }

}
